<template>
  <div class="register-page">
    <img class="register-page-top" src="@/assets/bg/top.svg" alt="" />
    <img class="register-page-bottom" src="@/assets/bg/bottom.svg" alt="" />
    <van-nav-bar title="注册" left-arrow @click-left="onBackClick" />
    <!-- 内容区 -->
    <div class="register-page-content">
      <div class="register-page-content-text">
        <div class="register-page-content-text-1">注册</div>
        <div class="register-page-content-text-2">欢迎使用易联智能！</div>
      </div>
      <div class="register-page-content-register">
        <van-form
          class="register-page-content-register-form"
          @submit="onSubmit"
        >
          <van-field
            v-model="username"
            center
            name="username"
            label="邮箱"
            placeholder="邮箱"
            :error-message="usererror"
            :rules="[{ validator, message: '请检查邮箱地址' }]"
          />
          <van-field
            v-model="password"
            center
            type="password"
            name="password"
            label="密码"
            placeholder="密码"
            :error-message="passwderror"
            :rules="[
              {
                validator,
                message:
                  '以字母开头，长度在6~18之间，只能包含字母、数字和下划线',
              },
            ]"
          />
          <van-field
            v-model="passwordconfirm"
            center
            type="password"
            name="password"
            label="确认密码"
            placeholder="确认密码"
            :error-message="passwderror"
            :rules="[{ required: true, message: '请确认密码' }]"
          />
          <van-field
            v-if="codeValidator(username)"
            v-model="code"
            center
            label="邮箱验证码"
            :rules="[{ required: true, message: '请填写验证码' }]"
          >
            <template #button>
              <div :style="sendBtnStyle" @click="onSendCode">
                <span v-if="sendOver">
                  <van-icon name="lock" />({{ time }}s)
                </span>
                <span v-else> 发送验证码 </span>
              </div>
            </template>
          </van-field>
          <div style="margin: 16px">
            <van-button
              style="
                margin-top: 20px;
                box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
              "
              round
              block
              type="info"
              native-type="submit"
              >注册</van-button
            >
          </div>
        </van-form>
      </div>
    </div>
  </div>
</template>

<script>
// import md5 from '@js/md5.min.js';
// import axios from'';
import { sendVeryCode, addUserByEmail } from "@/api/api";
import { Toast } from "vant";
export default {
  name: "login",
  components: {},
  data: function () {
    return {
      code: "",
      // 用户名
      username: "",
      // 密码
      password: "",
      passwordconfirm: "",
      // md5 加密的密码
      result: "",
      passwderror: "",
      usererror: "",
      sendBtnStyle: { color: "cornflowerblue" },
      sendOver: false,
      times: "",
      time: 60,
    };
  },
  created: function () {},
  methods: {
    showTime() {
      this.time--;
      if (this.time == 0) {
        clearInterval(this.times); //清除定时器
        this.time = 60;
        this.sendOver = false;
      }
    },
    stop() {
      this.sendOver = false;
      this.sendBtnStyle = { color: "cornflowerblue" };
    },
    onSendCode() {
      if (!this.sendOver) {
        if (/^\w+@[a-z0-9]+\.[a-z]{2,4}$/.test(this.username)) {
          Toast.loading("发送中...");
          let params = {
            EmailAddr: this.username,
          };
          sendVeryCode(params)
            .then((res) => {
              Toast.clear();
              if (res.returncode == 200) {
                Toast.success(res.description);
                this.sendBtnStyle = { color: "grey" };
                this.sendOver = true;
                this.times = setInterval(this.showTime, 1000);
                // setTimeout(this.stop(), 60 * 1000)
              } else {
                Toast.fail(res.description);
              }
            })
            .catch((err) => Toast.fail(err));
        } else {
          Toast.fail("请检查邮箱地址");
        }
      }
    },
    codeValidator(val) {
      return /^\w+@[a-z0-9]+\.[a-z]{2,4}$/.test(val);
    },
    validator(val, res) {
      if (res !== undefined) {
        if (res.message == "请检查邮箱地址") {
          return /^\w+@[a-z0-9]+\.[a-z]{2,4}$/.test(val);
        } else {
          return /^[a-zA-Z]\w{5,17}$/.test(val);
        }
      }
    },
    // 后退事件
    onBackClick: function () {
      this.$router.go(-1);
    },
    // 登录按钮点击事件
    onSubmit() {
      Toast.loading("注册中...");
      this.onLoginClick();
    },
    onLoginClick: function () {
      //localStorage.setItem("islogin",1);
      //this.$router.go(-1);
      this.result = this.$md5(this.password);
      console.log(this.username);
      // post
      // this.md5Password = md5(this.password);
      if (this.password !== this.passwordconfirm) {
        this.passwderror = "两次输入密码不一致";
      } else {
        let params = {
          username: this.username,
          code: this.code,
          passwd: this.result,
        };
        addUserByEmail(params)
          .then((res) => {
            Toast.clear();
            console.log(res);
            if (res.returncode == 200) {
              Toast.success(res.description);
              this.$router.push({
                name: "login",
                params: {
                  username: this.username,
                  passwd: this.password,
                  routerType: "back",
                },
              });
              // this.$router.go(-1);
            } else if (res.returncode === 400) {
              Toast.fail(res.description);
            }
          })
          .catch(function (error) {
            // alert(error.response.data.msg);
            console.log(error.response.data);
            console.log(error.response.status);
            // console.log(error.response.headers);
          });
        // this.$store.commit('setUsername', this.username);
        // this.$store.commit('setPhone', this.phone);
        // this.onBackClick();
      }
      // 判断当前的项目是运行在 Android 设备还是 IOS 设备中
      if (window.androidJSBridge) {
        // window 下存在 android 注入的对象（androidJSBridge），则表示当前项目在 android 设备中运行
        this.onLoginToAndroid();
      } else if (window.webkit) {
        // window 下存在 webkit ，表示当前项目在 IOS 设备中运行
        this.onLoginToIOS();
      }
    },
    /**
     * 忘记密码点击事件
     */
    onForgetPasswdClick: function () {
      this.$router.push({
        name: "resetpasswd",
        params: {
          routerType: "push",
        },
      });
    },
    /**
     * 立即注册点击事件
     */
    onToRegisterClick: function () {
      console.log("ok");
      this.$router.push({
        name: "register",
        params: {
          routerType: "push",
        },
      });
    },
    test: function () {
      this.axios
        .post("http://39.99.153.97:8081/package/packages", {
          phone: "18155348770",
        })
        .then((res) => {
          console.log(res);
          console.log(res.records);
          // console.log(JSON.stringify(res.records))
          this.$store.commit("aaddShoppingData", res.data.records);
        })
        .catch(function (error) {
          console.log(error.response.data);
          console.log(error.response.status);
          console.log(error.response.headers);
        });
      // this.$http.get('/goods').then(data => {
      //     console.log(data.list)
      //     this.goodsData = data.list;
      //     this.setSortGoodsData();
      //     this.initLayout();
      // });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@css/style.scss";

.register-page {
  // 页面组件过渡动画，脱离标准文档流
  position: absolute;
  height: 100%;
  width: 100%;
  background-color: white;
  &-top {
    position: absolute;
    right: 0;
    top: 46px;
  }
  &-bottom {
    position: absolute;
    left: 0;
    bottom: 0;
  }
  &-content {
    width: 100%;
    height: 100%;
    &-text {
      margin-top: 10vh;
      //font-family: PingFangSC-Regular;
      &-1 {
        font-size: 72px;
        color: #f7f7fb;
        letter-spacing: 0;
      }
      &-2 {
        //position: absolute;
        //bottom: 0;
        margin-left: 40px;
        float: left;
        font-size: 24px;
        color: #1d1e2c;
        letter-spacing: 0;
        transform: translateY(-48px);
      }
    }
    &-register {
      margin: 40px;
      &-form {
        padding: 0;
      }
      &-button {
        margin-top: 20px;
      }
    }
  }
}
.van-cell {
  margin: 0 0 10px 0;
  width: auto;
  border-radius: 10px;
  background: #f7f7fb;
}
</style>

